﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RecipeBookBusiness
{
    public class Flag
    {
        private RecipeBookEntities _entities = new RecipeBookEntities();
        private int _id;
        private int _recipeID;
        private bool _isSpam;
        private bool _toDelete;

        public Flag(int flagID)
        {
            loadFlagClass(flagID);
        }

        public Flag(int recipeID, bool? isSpam, bool? toDelete)
        {
            try
            {
                DeleteDataRow ddr = new DeleteDataRow();
                ddr.IDRecipe = recipeID;
                ddr.IsSpam = isSpam;
                ddr.ToDelete = toDelete;

                //Save to DB and get ID
                _entities.AddToDeleteDataRowSet(ddr);
                _entities.SaveChanges();
                int newFlagID = 0;
                foreach (DeleteDataRow idDdr in _entities.DeleteDataRowSet)
                {
                    if (idDdr.IDFlag > newFlagID)
                        newFlagID = idDdr.IDFlag;
                }
                loadFlagClass(newFlagID);
            }
            catch (Exception ex)
            {
                //TODO: Real exception handling
                Console.Write(ex.Message);
            }
        }

        private void loadFlagClass(int flagID)
        {
            DeleteDataRow ddr = (from c in _entities.DeleteDataRowSet
                                 where c.IDFlag == flagID
                                 select c).FirstOrDefault();

            _id = ddr.IDFlag;
            _recipeID = ddr.IDRecipe;
            _isSpam = (bool)ddr.IsSpam;
            _toDelete = (bool)ddr.ToDelete;
        }

        public void DeleteFlag()
        {
            DeleteDataRow ddr = (from c in _entities.DeleteDataRowSet
                                 where c.IDFlag == _id
                                 select c).FirstOrDefault();
            _entities.DeleteObject(ddr);
            _entities.SaveChanges();
        }

        public int ID
        {
            get
            {
                return _id;
            }
        }

        public int RecipeID
        {
            get
            {
                return _recipeID;
            }
        }

        public bool IsSpam
        {
            get
            {
                return _isSpam;
            }
        }

        public bool ToDelete
        {
            get
            {
                return _toDelete;
            }
        }
    }
}
